package com.eastfair.auth.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.eastfair.auth.dao.SystemLogMapper;
import com.eastfair.auth.entity.OrganizationRole;
import com.eastfair.auth.entity.SystemLog;
import com.eastfair.auth.service.SystemLogService;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.cache.auth.MenuRoleCacheKeyBuilder;
import com.eastfair.cache.auth.SystemLogCacheKeyBuilder;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.model.CacheKeyBuilder;

import com.eastfair.database.mybatis.conditions.Wraps;
import com.eastfair.database.mybatis.conditions.query.QueryWrap;
import com.eastfair.uid.baidu.rule.SnowFlakeRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;

import java.util.Collection;

//import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.aop.framework.AopContext;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.annotation.annotation.cache.Cache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
//import com.baomidou.dynamic.datasource.annotation.DS;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

import com.eastfair.auth.vo.*;
import com.eastfair.auth.dto.*;

/**
 * <p>
 * 业务实现类
 * 业务日志记录
 * </p>
 *
 * @author ligang
 * @date 2023-02-13
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class SystemLogServiceImpl extends SuperServiceImpl<SystemLogMapper, SystemLog> implements SystemLogService {

    @Autowired
    SnowFlakeRole snowFlakeRole;
    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(SystemLog model) {
        model.setId(snowFlakeRole.findUidSimple());
        if (ContextUtil.getProjectId() == null) {
            model.setProjectId(ContextUtil.getProjectId());
        }
        if (model.getSubsystemId() == null) {
            model.setSubsystemId(ContextUtil.getSubSystemId());
        }
        if (model.getTeamId() == null) {
            model.setTeamId(ContextUtil.getTeamId());
        }
        //雪花ID
        return R.successDef();
    }


    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<SystemLog> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<SystemLog> list(SystemLogDTO modelDTO, List<Long> ids) {
        return ((SystemLogService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'requestIp', #args[0]?.requestIp}," +
                            "{'ipAddr', #args[0]?.ipAddr}," +
                            "{'traceId', #args[0]?.traceId}," +
                            "{'type', #args[0]?.type}," +
                            "{'userId', #args[0]?.userId}," +
                            "{'userName', #args[0]?.userName}," +
                            "{'description', #args[0]?.description}," +
                            "{'classPath', #args[0]?.classPath}," +
                            "{'actionMethod', #args[0]?.actionMethod}," +
                            "{'requestUri', #args[0]?.requestUri}," +
                            "{'httpMethod', #args[0]?.httpMethod}," +
                            "{'params', #args[0]?.params}," +
                            "{'result', #args[0]?.result}," +
                            "{'exDetail', #args[0]?.exDetail}," +
                            "{'startTime', #args[0]?.startTime}," +
                            "{'finishTime', #args[0]?.finishTime}," +
                            "{'consumingTime', #args[0]?.consumingTime}," +
                            "{'ua', #args[0]?.ua}," +
                            "{'isSuccess', #args[0]?.isSuccess}," +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'teamId', #args[0]?.teamId}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<SystemLog> listOfCache(SystemLogDTO modelDTO, List<Long> ids) {
        //查询
        SystemLog queryModel = new SystemLog();
        if (modelDTO != null) {
            BeanUtils.copyProperties(modelDTO, queryModel);
        }

        QueryWrap<SystemLog> wrapper = Wraps.q(queryModel);
        if (ids != null && !ids.isEmpty()) {
            wrapper.lambda().in(SystemLog::getId, ids);
        }
        //添加其他业务查询条件
        wrapper.lambda().eq(SystemLog::getIsDeleted, BusinessConstant.DELETE_NO);
        List<SystemLog> modelList = list(wrapper);
        return modelList;
    }

    @Override
    public void batchSave(List<SystemLogDTO> systemLogDTOList) {
        if (CollectionUtil.isEmpty(systemLogDTOList)) {
            return;
        }
        List<SystemLog> systemLogList = new ArrayList<>();
        for (SystemLogDTO systemLogDTO : systemLogDTOList) {
            SystemLog systemLog = new SystemLog();
            BeanUtils.copyProperties(systemLogDTO, systemLog);
            handlerSave(systemLog);
            systemLogList.add(systemLog);
        }
        if (CollectionUtil.isEmpty(systemLogList)) {
            return;
        }
        System.out.println("插入记录：" + systemLogList.size());
        this.saveBatch(systemLogList);
    }


    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public SystemLogVO doToVo(SystemLog model) {
        if(model ==null){
            return null;
        }
        SystemLogVO modelVo = new SystemLogVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<SystemLogVO> doToVos(List<SystemLog> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<SystemLogVO> result = new ArrayList<>();
        for (SystemLog model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }

//    @Override
//    public CacheKeyBuilder getCacheKeyBuilder() {
//        return new SystemLogCacheKeyBuilder();
//    }
}
